<template>
<!--  //分页功能-->
  <div class="pagination-container" v-if="totalPages > 1">
    <button @click="changePage(currentPage - 1)" :disabled="currentPage === 1" class="page-btn">
      «
    </button>
    <button
      v-for="page in pages"
      :key="page"
      @click="changePage(page)"
      :class="['page-btn', { active: page === currentPage }]"
      :disabled="page === '...'">
      {{ page }}
    </button>
    <button @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages" class="page-btn">
      »
    </button>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';

const props = defineProps({
  currentPage: { type: Number, required: true },
  totalPages: { type: Number, required: true },
  maxVisibleButtons: { type: Number, default: 7 }
});

const emit = defineEmits(['page-changed']);

const changePage = (page: number | string) => {
  if (typeof page === 'number' && page >= 1 && page <= props.totalPages) {
    emit('page-changed', page);
  }
};

const pages = computed(() => {
  const { currentPage, totalPages, maxVisibleButtons } = props;
  const pagesToShow: (number | string)[] = [];

  if (totalPages <= maxVisibleButtons) {
    for (let i = 1; i <= totalPages; i++) {
      pagesToShow.push(i);
    }
  } else {
    let startPage = Math.max(1, currentPage - Math.floor((maxVisibleButtons - 3) / 2));
    let endPage = Math.min(totalPages, startPage + maxVisibleButtons - 3);

    if (endPage - startPage < maxVisibleButtons - 3) {
      startPage = Math.max(1, endPage - maxVisibleButtons + 3);
    }

    pagesToShow.push(1);
    if (startPage > 2) {
      pagesToShow.push('...');
    }

    for (let i = startPage; i <= endPage; i++) {
      if (i !== 1 && i !== totalPages) {
        pagesToShow.push(i);
      }
    }

    if (endPage < totalPages - 1) {
      pagesToShow.push('...');
    }
    pagesToShow.push(totalPages);
  }
  return pagesToShow;
});
</script>

<style scoped>
@import '@/assets/styles/components/Pagination.css';
</style>
